package com.allqj.sfx.ddd.member.infrastructure.repository;

import com.allqj.sfx.ddd.member.domain.entity.flow.FlowInstanceTask;
import com.allqj.sfx.ddd.member.domain.repository.FlowInstanceTaskRepository;
import com.allqj.sfx.ddd.member.infrastructure.dao.FlowInstanceTaskDAO;
import com.allqj.sfx.ddd.member.infrastructure.po.FlowInstanceTaskDO;
import com.allqj.sfx.ddd.member.infrastructure.converter.FlowInstanceTaskConverter;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author sjw
 * @className FlowInstanceTaskRepositoryImpl
 * @date 2022/7/22 11:22
 * @description: FlowInstanceTaskRepository具体实现
 * Repository接口定义位于domain层
 * Repository接口具体实现位于infrastructure层
 * 与底层db解耦
 */
@Repository
public class FlowInstanceTaskRepositoryImpl implements FlowInstanceTaskRepository {

    private final FlowInstanceTaskDAO dao;

    public FlowInstanceTaskRepositoryImpl(FlowInstanceTaskDAO dao) {
        this.dao = dao;
    }

    @Override
    public FlowInstanceTask flowInstanceTask(Integer id) {
        Optional<FlowInstanceTaskDO> flowInstanceTaskDO = dao.findById(id);
        return flowInstanceTaskDO.map(instanceTaskDO -> FlowInstanceTaskConverter.INSTANCE.do2Entity(instanceTaskDO)).orElse(null);
    }

    @Override
    public List<FlowInstanceTask> save(List<FlowInstanceTask> flowInstanceTasks) {
        if (flowInstanceTasks == null) return null;
        return flowInstanceTasks.stream().map(this::save).collect(Collectors.toList());
    }

    @Override
    public FlowInstanceTask save(FlowInstanceTask flowInstanceTask) {
        if (flowInstanceTask == null) return null;
        FlowInstanceTaskDO flowInstanceTaskDO = FlowInstanceTaskConverter.INSTANCE.entity2Do(flowInstanceTask);
        flowInstanceTaskDO = dao.save(flowInstanceTaskDO);
        return FlowInstanceTaskConverter.INSTANCE.do2Entity(flowInstanceTaskDO);
    }

}
